package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDto;
import com.sky.entity.ShoppingCart;
import com.sky.result.Result;
import com.sky.service.IShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/shoppingCart")
@Slf4j
public class ShoppingCartController {
    @Autowired
    private IShoppingCartService shoppingCartService;

    /**
     * 购物车添加商品
     * @param shoppingCartDto
     * @return
     */
    @PostMapping("/add")
    public Result<String> save(@RequestBody ShoppingCartDto shoppingCartDto){
        //log.info("{}",shoppingCartDto.toString()); 测试成功
        boolean flag=shoppingCartService.modify(shoppingCartDto);
        if (!flag) {
            shoppingCartService.save(shoppingCartDto);
        }
        return Result.success();
    }

    /**
     * 查看购物车所有信息
     * @return
     */
    @GetMapping("/list")
    public Result<List<ShoppingCart>> list(){
        Long userId= BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts= shoppingCartService.list(userId);
        return Result.success(shoppingCarts);
    }

    /**
     * 删除购物车的一个商品
     * @param shoppingCartDto
     * @return
     */
    @PostMapping("/sub")
    public Result<String> sub(@RequestBody ShoppingCartDto shoppingCartDto){
        shoppingCartService.sub(shoppingCartDto);
        return Result.success();
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public Result<String> clean(){
        shoppingCartService.empty();
        return Result.success();
    }
}
